package com.start.common.tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class StartRedisLockTools {

    @Autowired
    private StartRedisTools redisTools;


    /**
     * 获取锁
     *
     * @param key
     * @param milliseconds
     * @return
     */
    public boolean Lock(String key, Long milliseconds) {
        if (milliseconds == null) {
            milliseconds = 60L;
        }

        Boolean lock = redisTools.getStringRedisTemplate().opsForValue().setIfAbsent("start:lock:" + key, "lock", milliseconds, TimeUnit.MILLISECONDS);
        return Boolean.TRUE.equals(lock);
    }

    public boolean hasLock(String key) {
        return Boolean.TRUE.equals(redisTools.getStringRedisTemplate().hasKey("start:lock:" + key));
    }


    /**
     * 释放锁
     *
     * @param key
     */
    public void unLocal(String key) {
        redisTools.getStringRedisTemplate().delete("start:lock:" + key);
    }
}
